<template>
  <div class="phone">
    <div class="phone-content" v-if="isShowSendCode">
      <div class="phone-title">
        使用您的账户
        <span v-if="isBindPhone !== 0" key="loginKey">登录</span>
        <span v-else key="bindKey">绑定</span>
      </div>
      <div class="phone-tips">
        <span>
          一条验证码已发送到手机后四位{{lastNumber}}的手机，请输入验证码继续
        </span>
      </div>
      <div class="code">
        
        <div class="login-input-row">
          <div class="login-label">验证码</div>
          <div class="login-input">
            <input
              class="login-inp"
              name="sms"
              ref="smsInp"
              v-validate="'required|onlyRule0'"
              v-model="codeNumbs" 
              type="text"
              autofocus="autofocus"
              :maxlength="6"
              @keyup.enter="continueLast"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('sms')" class="el-form-item__error">
            {{ errors.first("sms") }}
          </div>
        </div>
      </div>
      <div class="send">
        <div
          @click="reSend"
          :disabled="disabled"
          class="send-code blueColor"
          :class="{'grayColor': disabled}"
        >
          重新发送验证码
          <span v-if="isShowCountNumber">({{ count }})s</span>
        </div>
      </div>
      <div class="step-btns">
        <div class="step-btn" @click="goBackPhone">返回</div>
        <div @click="continueLast" class="step-btn active">继续</div>
      </div>
    </div>
    <other-way />

    <set-pwd v-if="pwdVisible" @comfirm="comfirm" />
  </div>
</template>

<script>
import * as api from "@/api";
export default {
  // 0 是代表没有绑定 1是代表已经绑定
  props: {
    isBindPhone: {
      type: Number,
      default: 1,
    },
    lastNumber: {
      type: String,
    },
    phoneNums: {
      type: String,
    },
  },
  data() {
    return {
      codeNumbs: '',
      count: 60,
      timer: "",
      isShowCountNumber: true,
      disabled: true,
      isShowPassword: false, // 手机号
      isShowSendCode: true, // 验证码
      verifyData: {},
      pwdVisible: false,
      pwd: '',
      hasPwd: 1,
      loginResData: null
    };
  },

  methods: {
    keyDown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false
      }
    },
    // 60s倒计时
    getCode() {
      console.log('sms开始倒计时了： ')
      const time_total = 60;
      if (!this.timer) {
        this.isShowCountNumber = true;
        this.disabled = true;
        this.count = time_total;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= time_total) {
            this.count--;
          } else {
            this.isShowCountNumber = false;
            this.disabled = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },

    
    reSend() {
      if (this.disabled) {
        return false;
      }
      this.loginSmsVerifyCode();
    },
    // 返回上一级
    goBackPhone() {
      this.isShowSendCode = false;
      this.$emit("goBackPhone", false)
    },

    continuePhone() {
      let phone = this.phoneNums
      if (phone && phone.length == 11 && /^1[3-9]\d{9}$/.test(phone)) {
        this.lastNumber = phone.substr(phone.length - 4);
        this.loginSmsVerifyCode();
      } else if (phone.length === 0) {
        this.$message.warning("手机号不能为空");
        return false;
      } else {
        this.$message.warning("请输入正确的手机号");
        return false;
      }
    },

    continueLast() {

      if (!this.codeNumbs || this.codeNumbs.length !== 6 || isNaN(this.codeNumbs)) {
        this.$message.warning("验证码必须是6位数字");
        return false;
      }
      this.verifyData = {
        phone: this.phoneNums,
        code: this.codeNumbs,
      };
      
      // 0 没有手机号
      if (this.isBindPhone == 0) {
        this.loginBindPhone();
      } else {
        this.loginVerifyCode();
      }
    },
    setStorage(data) {
      localStorage.setItem("access_token", data.access_token);
      localStorage.setItem("refresh_token", data.refresh_token);
      localStorage.setItem("username", data.name);
      localStorage.setItem("organization_id", data.organization_id);
      localStorage.setItem("user_id", data.user_id);
    },
    
    setLoginData(data) {
      localStorage.setItem("access_token", data.access_token)
      this.loginResData = data
    },
    
    comfirm(pwd) {
      this.pwd = pwd
      this.loginResetPassword()
    },

    loginSuc(data) {
      this.setStorage(data)
      this.$store.commit("handleUserRole", data.role_name); // 角色
      this.$store.commit("handleAltered", data.altered);
      let permission = JSON.parse(data.permission);
      if (this.$store.state.user_role === "超级管理员") {
        for (let i in JSON.parse(data.permission)) {
          this.$set(permission[i], "addChecked", true);
          this.$set(permission[i], "editChecked", true);
          this.$set(permission[i], "deletChecked", true);

        }
        localStorage.setItem("permission", JSON.stringify(permission));
      } else {
        localStorage.setItem("permission", data.permission);
      }
      this.$emit("continueLast", data);
    },

    // 4.1.9、重置密码
    async loginResetPassword() {
      const { code, data } = await api.login(this).loginResetPassword({
        user_id: this.loginResData.user_id,
        type: this.loginResData.organization_id != null ? 1 : 0,
        password: window.btoa(this.pwd)
      })
      if (code === 0) {
        this.loginSuc(this.loginResData)
      }
    },

    // 发送短信验证码
    async loginSmsVerifyCode() {
      let params = {};
      params.phone = this.phoneNums
      const { code, data, message } = await api
        .login(this)
        .smsVerifyCode(params);
      if (code === 0) {
        

        if (this.isBindPhone === 1) {
          // localStorage.setItem("access_token", data.access_token);
        }
        this.isShowSendCode = true;
        this.getCode();
        this.$emit("continuePhoneSendCode", this.isShowPhone);
      }
    },
    // 短信验证码登录
    async loginVerifyCode() {
      const { code, data } = await api
        .login(this)
        .loginVerifyCode(this.verifyData);
      if (code === 0) {
        // 0---否  1 ---已经设置过密码
        this.hasPwd = data.has_password
        if (data.has_password == 0) {
          // 没有设置过密码
          this.setLoginData(data)
          this.pwdVisible = true

        } else {
          this.loginSuc(data)
        }
      }
    },

    // 手机发送短信验证码
    async loginBindPhone() {
      console.log("什么时候进来的来呢----");
      const { code, data, message } = await api.login(this).loginBindPhone(this.verifyData);
      if (code === 0) {
        if (process.env.VUE_APP_ENV === "development") {
          window.location.href = `http://localhost:6500/control`;
        } else {
          const { protocol, host } = window.location
          window.location.href = `${protocol}//${host}/control`;
        }
      }
    },
  },
  created() {
    this.getCode();
  },
  mounted () {
    setTimeout(() => {
      this.$refs.smsInp.focus()
    }, 800)
  },
  beforeDestroy() {
    this.codeNumbs = ''
  },
  destroyed() {
    clearInterval(this.timer);
  },
};
</script>

<style>
</style>